package com.gjy.disruptor.uuid.newd.netty;

import com.gjy.disruptor.uuid.newd.dis.UuidEventHandler;
import com.gjy.disruptor.uuid.newd.dis.UuidEventProducer;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Netty请求处理器，处理HTTP请求并发布到Disruptor。
 *
 * @author gjy
 * @version 1.0
 * @since 2025-10-11 10:21:32
 */
public class UuidRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private static final Logger logger = LoggerFactory.getLogger(UuidRequestHandler.class);

    private final UuidEventProducer producer;

    public UuidRequestHandler(UuidEventProducer producer) {
        this.producer = producer;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) {
        // 检查请求路径是否为 /uuid
        if (!request.uri().equals("/uuid")) {
            sendErrorResponse(ctx, HttpResponseStatus.NOT_FOUND);
            return;
        }

        // 检查请求方法是否为GET
        if (request.method() != HttpMethod.GET) {
            sendErrorResponse(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
            return;
        }

        try {
            // 直接将请求发布到Disruptor
            long requestId = UuidEventHandler.nextRequestId();
            if (!producer.tryProduce(ctx, requestId)) {
                // 如果RingBuffer满了，返回服务不可用
                sendErrorResponse(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE);
            }
            // 注意：这里不等待响应，响应由Disruptor消费者直接发送

        } catch (Exception e) {
            logger.error("Error processing request", e);
            sendErrorResponse(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        }
    }

    private void sendErrorResponse(ChannelHandlerContext ctx, HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                status);
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);

        ctx.writeAndFlush(response).addListener(io.netty.channel.ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.debug("Exception in handler for {}: {}", ctx.channel().remoteAddress(), cause.getMessage());
        ctx.close();
    }

}
